package linda.server;


import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

import linda.Callback;
import linda.Linda.eventMode;
import linda.Linda.eventTiming;
import linda.shm.CentralizedLinda;
import linda.Tuple;


public class LindaServer extends UnicastRemoteObject implements InterfaceServer {

		protected LindaServer() throws RemoteException {
		super();
	}

	private CentralizedLinda localLinda = new CentralizedLinda();

		public void DoCallBack(eventMode mode, eventTiming timing,
				Tuple template, InterfaceRemoteCallback c) throws RemoteException {
			localLinda.eventRegister(mode, timing, template, new Interncallback(c));
		}

		@Override
		public Object DoWork(method m, Tuple tuple) throws RemoteException {
			switch (m) {
			case READ: 	return localLinda.read(tuple);
			case TAKE: 	return localLinda.take(tuple);
			case TRYTAKE: return localLinda.tryTake(tuple);
			case TRYREAD: return localLinda.tryRead(tuple);
			case TAKEALL: return localLinda.takeAll(tuple);
			case READALL: return localLinda.readAll(tuple);
			case WRITE:  localLinda.write(tuple); return null;
				default:
					return null;
			}
			
		}
		
		//Classe gerant le callback local et l appel vers les callback client
		class Interncallback implements Callback {
			private InterfaceRemoteCallback callback;
			
			public Interncallback(InterfaceRemoteCallback c) {
				this.callback = c;
			}
			
			public void call(Tuple t) {
				//on appelle le callback du client
				try {
					callback.call(t);
				} catch (RemoteException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		}
}
